import React, { useState } from 'react';
import { connect } from 'react-redux';
import './index.scss'
import axios from 'axios';


function Weather(props) {
  const [weatherData, setWeatherData] = useState([])
  // -----------加载界面获取天气数据--------------------
  React.useEffect(() => {
    getWeatherData()
  }, [])
  // 异步获取后台数据
  async function getWeatherData() {
    const res = await axios.get('http://localhost:8080/API/weather')
    setWeatherData(res.data.data.list)
  }

  // ---------------城市信息组件渲染-------------------
  function cityItemRender() {
    return (
      weatherData.map((item) => {
        const { id, city, date, data } = item
        const { temperature, info, power, direct } = data
        return (
          <div className='cityItem' key={id}>
            <p>city:{city}</p>
            <p>date:{date}</p>
            <p>tem:{temperature}</p>
            <p>info:{info}</p>
            <p>wind:{direct + power}</p>
          </div>
        )
      })
    )
  }

  // ------redux保存/获取天气数据-----------------------
  function saveDataToRedux() {
    props.saveWeather(weatherData)
    alert('保存数据成功')
  }
  function getDataFromRedux() {
    props.getWeather()
    alert('获取数据成功')
  }

  // --------------------------------------------------------
  return (
    <div className='dragBox'>
      <div className='title'>天气信息</div>
      {/* ----------循环遍历城市--------- */}
      {cityItemRender()}
      <div className='button-group'>
        <button onClick={saveDataToRedux}>保存数据到redux</button>
        <button onClick={getDataFromRedux}>获取redux数据</button>
      </div>
    </div>
  );
}


// 映射redux中的state到Props
const mapStateToProps = (state) => ({ weatherReducer: state.weatherReducer })
// 映射方法
const mapDispatchToProps = (dispatch) => ({
  saveWeather: (weatherData) => dispatch({ type: 'saveWeather', data: weatherData }),
  getWeather: () => dispatch({ type: 'getWeather' }),
})

// 连接组件和store
export default connect(mapStateToProps, mapDispatchToProps)(Weather);